import {Modal, Transfer, Table} from 'antd';
import {useEffect, useState, useCallback} from 'react';
import difference from 'lodash/difference';
import {connect} from 'umi';
import styles from './styles.less';

const TableTransfer = ({leftColumns, rightColumns, ...restProps}) => (
  <Transfer {...restProps}>
    {({
        direction,
        filteredItems,
        onItemSelectAll,
        onItemSelect,
        selectedKeys: listSelectedKeys,
        disabled: listDisabled,
      }) => {
      const columns = direction === 'left' ? leftColumns : rightColumns;
      const rowSelection = {
        getCheckboxProps: (item) => ({
          disabled: listDisabled || item.disabled,
        }),
        onSelectAll(selected, selectedRows) {
          const treeSelectedKeys = selectedRows
            .filter((item) => !item.disabled)
            .map(({key}) => key);
          const diffKeys = selected
            ? difference(treeSelectedKeys, listSelectedKeys)
            : difference(listSelectedKeys, treeSelectedKeys);
          onItemSelectAll(diffKeys, selected);
        },
        onSelect({key}, selected) {
          onItemSelect(key, selected);
        },
        selectedRowKeys: listSelectedKeys,
      };
      return (
        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={filteredItems}
          size="small"
          style={{
            pointerEvents: listDisabled ? 'none' : undefined,
          }}
          onRow={({key, disabled: itemDisabled}) => ({
            onClick: () => {
              if (itemDisabled || listDisabled) return;
              onItemSelect(key, !listSelectedKeys.includes(key));
            },
          })}
        />
      );
    }}
  </Transfer>
);


const DataForm = (props) => {
  const {dispatch, submitting, salerList} = props;
  const {salersSetting, dataForm, setDataForm, tablePayload, setTablePayload} = props.data;
  const [targetKeys, setTargetKeys] = useState([]);

  /* 获取列表 */
  const fetchList = useCallback((payload) => {
    dispatch({
      type: 'CampainCommon/fetchCampainSalerList',
      payload: payload,
    });
  }, [dispatch]);

  /* 获取数据 */
  useEffect(() => {
    if (salersSetting) {
      fetchList({notCampainId: salersSetting.data.id});
    }
  }, [fetchList, dataForm, salersSetting]);

  /* 确定操作 */
  function onOk() {
    if (submitting) {
      return;
    }
    if (targetKeys.length <= 0) {
      return;
    }
    dispatch({
      type: 'POperationCampainSalersSetting/add',
      payload: {campainId: salersSetting.data.id, salerIds: targetKeys},
      callback: () => {
        onCancel();
        setTablePayload({...tablePayload});
      },
    });
  }

  /* 取消操作 */
  function onCancel() {
    setDataForm(undefined);
    setTargetKeys([]);
    dispatch({
      type: 'CampainCommon/chgSalerList',
      payload: []
    });
  }

  /* 监听 Transfer 数据变化 */
  const onChange = (nextTargetKeys) => {
    setTargetKeys(nextTargetKeys);
  };

  /* 左边表格列 */
  const leftTableColumns = [
    {
      dataIndex: 'name', ellipsis: false, title: '用户名称', render: (_, record) => {
        return record.name ? (<span>{record.name}</span>) : '-';
      }
    },
    {
      dataIndex: 'mobile', ellipsis: false, title: '手机号码', render: (_, record) => {
        return record.mobile ? (<span>{record.mobile}</span>) : '-';
      }
    },
  ];

  /* 右边边表格列 */
  const rightTableColumns = [
    {
      dataIndex: 'name', ellipsis: false, title: '用户名称', render: (_, record) => {
        return record.name ? (<span>{record.name}</span>) : '-';
      }
    },
    {
      dataIndex: 'mobile', ellipsis: false, title: '手机号码', render: (_, record) => {
        return record.mobile ? (<span>{record.mobile}</span>) : '-';
      }
    },
  ];

  return (
    <Modal
      confirmLoading={submitting}
      title={dataForm ? dataForm.title : ''}
      open={dataForm ? dataForm.visible : false}
      onOk={onOk}
      onCancel={onCancel}
      forceRender={true}
      width={800}
      bodyStyle={{paddingTop: 0}}
      className={styles.myTransfer}
    >
      <TableTransfer
        dataSource={salerList}
        targetKeys={targetKeys}
        showSearch={true}
        onChange={onChange}
        filterOption={(inputValue, item) => item.name.indexOf(inputValue) !== -1 || item.mobile.indexOf(inputValue) !== -1}
        leftColumns={leftTableColumns}
        rightColumns={rightTableColumns}
      />
    </Modal>
  );
};


export default connect(({loading, CampainCommon}) => {
  return {
    loading: loading.effects['CampainCommon/fetchCampainSalerList'],
    submitting: loading.effects['POperationCampainSalersSetting/add'],
    salerList: CampainCommon.salerList,
  };
})(DataForm);

